package org.lfh.wintersun.web.secondKill.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.lfh.wintersun.common.base.PageUtils;
import org.lfh.wintersun.utils.LoginUserHolder;
import org.lfh.wintersun.utils.redis.Lock;
import org.lfh.wintersun.web.secondKill.dao.SecondKillOrderDao;
import org.lfh.wintersun.web.secondKill.entity.SecondKillOrderEntity;
import org.lfh.wintersun.web.secondKill.entity.SecondKillVoucherEntity;
import org.lfh.wintersun.web.secondKill.entity.SecondKillVoucherExtEntity;
import org.lfh.wintersun.web.secondKill.service.SecondKillOrderService;
import org.lfh.wintersun.web.secondKill.service.SecondKillVoucherExtService;
import org.lfh.wintersun.web.secondKill.service.SecondKillVoucherService;
import org.springframework.aop.framework.AopContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * (SecondKillOrder)表服务实现类
 *
 * @author lfh
 * @since 2025-04-12 22:36:31
 */
@Slf4j
@Service("secondKillOrderService")
public class SecondKillOrderServiceImpl extends ServiceImpl<SecondKillOrderDao, SecondKillOrderEntity>
        implements SecondKillOrderService {

    @Resource
    private SecondKillVoucherService secondKillVoucherService;
    @Resource
    private SecondKillVoucherExtService secondKillVoucherExtService;
    @Resource
    private Lock lock;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public SecondKillOrderEntity queryById(Long id) {
        return this.getById(id);
    }

    /**
     * 分页查询
     *
     * @param pageNum 页码
     * @param size    每页数量
     * @return 分页结果
     */
    @Override
    public PageUtils<SecondKillOrderEntity> queryByPage(Integer pageNum, Integer size) {
        //TODO 分页查询
        IPage<SecondKillOrderEntity> iPage =
                this.baseMapper.queryAllByLimit(new Page<>(pageNum, size));
        return new PageUtils<>(iPage);
    }

    /**
     * 新增数据
     *
     * @param secondKillOrderEntity 实例对象
     * @return 实例对象
     */
    @Override
    public SecondKillOrderEntity insert(SecondKillOrderEntity secondKillOrderEntity) {
        this.save(secondKillOrderEntity);
        return secondKillOrderEntity;
    }

    /**
     * 修改数据
     *
     * @param secondKillOrderEntity 实例对象
     * @return 实例对象
     */
    @Override
    public SecondKillOrderEntity update(SecondKillOrderEntity secondKillOrderEntity) {
        this.updateById(secondKillOrderEntity);
        return secondKillOrderEntity;
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     */
    @Override
    public void deleteById(Long id) {
        this.removeById(id);
    }

    /**
     * 通过主键集合删除数据
     *
     * @param ids 主键集合
     */
    @Override
    public void deleteIds(List<Long> ids) {
        super.removeByIds(ids);
    }

    @Override
    public SecondKillOrderEntity secondKill(Long voucherId) {
        SecondKillVoucherEntity voucherEntity = secondKillVoucherService.queryById(voucherId);
        if (voucherEntity == null) {
            throw new RuntimeException("优惠卷不存在id:" + voucherId);
        }
        SecondKillVoucherExtEntity secondKillVoucherExtEntity = voucherEntity.getSecondKillVoucherExtEntity();
        if (secondKillVoucherExtEntity == null) {
            throw new RuntimeException("非秒杀id:" + voucherId);
        }
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime beginTime = secondKillVoucherExtEntity.getBeginTime();
        LocalDateTime endTime = secondKillVoucherExtEntity.getEndTime();
        if (now.isBefore(beginTime)) {
            throw new RuntimeException("秒杀未开始！");
        }
        if (now.isAfter(endTime)) {
            throw new RuntimeException("秒杀已结束！");
        }

        //一人一单
        Long userId = LoginUserHolder.getUserId();
        SecondKillOrderEntity secondKillOrderEntity = null;
        String threadId = Thread.currentThread().getId() + "";
        //分布式锁
        try {
            boolean b = lock.tryLock("lock:order:" + userId, threadId);
            if (!b) {
                throw new RuntimeException("系统繁忙！");
            }
            SecondKillOrderService proxy = (SecondKillOrderService) AopContext.currentProxy();
            secondKillOrderEntity = proxy.getSecondKillOrderEntity(voucherId, secondKillVoucherExtEntity);
        } finally {
            lock.unlock("lock:order:" + userId, threadId);
        }

        return secondKillOrderEntity;
    }

    @Transactional(rollbackFor = Exception.class)
    public SecondKillOrderEntity getSecondKillOrderEntity(Long voucherId, SecondKillVoucherExtEntity secondKillVoucherExtEntity) {
        LambdaQueryWrapper<SecondKillOrderEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SecondKillOrderEntity::getVoucherId, voucherId);
        queryWrapper.eq(SecondKillOrderEntity::getUserId, LoginUserHolder.getUserId());
        long count = this.count(queryWrapper);
        if (count > 0) {
            throw new RuntimeException("一人只能购买一单！");
        }

        //1.查询库存
        Integer stock = secondKillVoucherExtEntity.getStock();
        if (stock <= 0) {
            log.info("当前库存值:{}", stock);
            throw new RuntimeException("库存不足！");
        }
        //2.扣除库存
        LambdaUpdateWrapper<SecondKillVoucherExtEntity> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SecondKillVoucherExtEntity::getVoucherId, voucherId);
        updateWrapper.setSql("stock = stock - 1");
        //a.使用数据库锁，保证的超卖问题，但是成功率低
//        updateWrapper.eq(SecondKillVoucherExtEntity::getStock, stock);
        //b.优化为stock>0,即可 成功率低
        updateWrapper.gt(SecondKillVoucherExtEntity::getStock, 0);
        boolean update = secondKillVoucherExtService.update(updateWrapper);

        SecondKillOrderEntity secondKillOrderEntity = new SecondKillOrderEntity();
        if (update) {
            //3.创建订单
            secondKillOrderEntity.setUserId(LoginUserHolder.getUserId());
            secondKillOrderEntity.setVoucherId(voucherId);
            secondKillOrderEntity.setStatus(1);
            this.insert(secondKillOrderEntity);
        } else {
            throw new RuntimeException("系统繁忙！");
        }
        return secondKillOrderEntity;
    }
}
